package com.itic.mall.mobile.users.model;

import com.itic.mall.system.users.usermodel.service.UsersModelService;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.type.CouponState;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.users.usercoupon.persistence.model.UsersCoupon;
import com.itic.mall.system.users.usercoupon.persistence.model.UsersCouponExample;
import com.itic.mall.system.users.usercoupon.service.UsersCouponService;
import com.itic.mall.system.users.usermodel.persistence.model.UsersModel;
import com.itic.mall.system.users.usermodel.persistence.model.UsersModelExample;
import com.itic.mall.system.users.usersmall.service.UsersMallService;
import com.itic.mall.system.users.userstoken.persistence.model.UsersToken;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample;
import com.itic.mall.system.users.usermodelscrollrel.service.UsersModelScrollRelService;
import com.itic.mall.system.users.usermodelscrollrel.persistence.model.UsersModelScrollRel;
import com.itic.mall.system.users.usermodelscrollrel.persistence.model.UsersModelScrollRelExample;
import com.itic.mall.system.users.usermodelscrollrel.persistence.model.UsersModelScrollRelExample.Criteria;

/**
 * 用户模块信息展示接口
 */
/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value="/mobile/users")
public class UsermodelInterface extends BaseMobileInterface{
	
	@Autowired 
	private UsersModelService usermodelService;
	@Autowired 
	private UsersModelScrollRelService usersModelScrollRelService;
	@Autowired 
	private UsersCouponService usersCouponService;
	
    //private static String[] ignoreProperties = new String[] { "createUser", "isEffective", "updateTime", "orgCode" };

    /**
     * 用户绑定微信
     * @param request
     * @param response
     * @param token
     * @param appId
     * @param unionid
     * @param userNickName
     * @param userHeadImg
     * @return
     */
    @RequestMapping(value="/bindwx")
	@ResponseBody
	public Map<String,Object> bindwx(HttpServletRequest request,HttpServletResponse response,String token,String appId,String unionid,String userNickName,String userHeadImg ){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	    	if(StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(unionid) ){
	    		UsersMall user = getUsersByTokenAndAppId(token, appId);
	    		if( null != user ){
	    			//判断unionid 是否已绑定其它的用户，如果没有绑定就可以
	    			UsersMall usersByUnionid = getUsersByUnionid(unionid);
	    			if( null == usersByUnionid ){
	    				user.setUnionid(unionid);
	    				if( StringHelper.isBlank(userNickName) && StringHelper.isNotBlank(userNickName) ){
	    					user.setUserNickName(userNickName);
	    				}
	    				if( getDefaultHeadImg().equals(user.getUserHeadImg()) && StringHelper.isNotBlank(userHeadImg) ){
	    					user.setUserHeadImg(userHeadImg);
	    				}
	    				usersMallService.edit(user);
	    				errorCode = SUCCESS_ERROR_CODE;
		    	       	errorMsg = SUCCESS_ERROR_MSG;
	    			}else{
	    				errorCode = UNIONID_BINED_ERROR_CODE;
		    	       	errorMsg = UNIONID_BINED_ERROR_MSG;
	    			}
	    		}else{
	    			errorCode = LOGIN_ERROR_CODE;
	    	       	errorMsg = LOGIN_ERROR_MSG;
	    		}
	    	}
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UsermodelInterface", "bindwx", e.toString(),"用户模块信息展示接口",e);
	    }
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
	    return resultMap;
	}
	
	@RequestMapping(value="/showmodel")
	@ResponseBody
	public Map<String,Object> showmodel(HttpServletRequest request,HttpServletResponse response,String token,String appid){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	    	if(StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appid)){
	    		UsersMall usersMall = getUsersByTokenAndAppId(token,appid);
		    	if(usersMall != null){
		    		String userid = usersMall.getId();
		    		UsersModelExample example = new UsersModelExample();
		    		com.itic.mall.system.users.usermodel.persistence.model.UsersModelExample.Criteria criteria = example.createCriteria();
		    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		    		criteria.andIsVisibleEqualTo(DBConst.TRUE);
		    		criteria.andUserIdEqualTo(userid);
			   		this.handlePageQueryDefault(request, example);//分页
		    		List<UsersModel> list = usermodelService.list(example);
		    		if(list != null){
		    			errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
						resultMap.put(DATA, list);
		    		}else{
		    			errorCode = USER_MODEL_ERROR_CODE;
		    			errorMsg = USER_MODEL_ERROR_MSG;
		    		}
		    	}else{
		    		errorCode = LOGIN_ERROR_CODE;
		    		errorMsg = LOGIN_ERROR_MSG;
		    	}
	    	}
	    	
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UsermodelInterface", "showmodel", e.toString(),"用户模块信息展示接口",e);
	    }
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
	    return resultMap;
	}
	@RequestMapping(value="/showcroll")
	@ResponseBody
	public Map<String,Object> showcroll(HttpServletRequest request,HttpServletResponse response,String token,String appid){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	    	UsersMall usersMall = getUsersByTokenAndAppId(token,appid);
	    	if(StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appid)){
	    		if(usersMall != null ){
		    		String userid = usersMall.getId();
		    		UsersModelScrollRelExample example = new UsersModelScrollRelExample();
		    		com.itic.mall.system.users.usermodelscrollrel.persistence.model.UsersModelScrollRelExample.Criteria criteria = example.createCriteria();
		    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		    		criteria.andIsVisibleEqualTo(DBConst.TRUE);
		    		criteria.andUserIdEqualTo(userid);
			   		this.handlePageQueryDefault(request, example);//分页
		    		List<UsersModelScrollRel> list = usersModelScrollRelService.list(example);
		    		if(list.size()>0){
		    			errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
						resultMap.put(DATA, list);
		    		}else{
		    			errorCode = USER_MODEL_SCROLL_REL_ERROR_CODE;
		    			errorMsg = USER_MODEL_SCROLL_REL_ERROR_MSG;
		    		}
		    	}else{
		    		errorCode = LOGIN_ERROR_CODE;
		    		errorMsg = LOGIN_ERROR_MSG;
		    	}
	    	}
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UsermodelInterface", "showcroll", e.toString(),"用户模块条幅展示接口",e);
	    }
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
	    return resultMap;
	}
	
	/**
	 * 我的红包
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value="/mycoupon")
	@ResponseBody
	public Map<String,Object> mycoupon(HttpServletRequest request,HttpServletResponse response,String token,String appId){
		Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   		if(StringHelper.isNotBlank(token)&& StringHelper.isNotBlank(appId)){
	   			UsersMall usersMall = getUsersByTokenAndAppId(token,appId);
	   			if(usersMall != null){
   					Date date = new Date();
	   				List<UsersCoupon> list = usersCouponService.getUsersCouponByUserId(usersMall.getId(),CouponState.sys,"");
	   				List<Map<String, Object>> couponList = new ArrayList<>();
	   				if(!list.isEmpty()){
						for(UsersCoupon coupon : list) {
							Map<String, Object>  couponMap = new HashMap<>();
							couponMap.put("id", coupon.getId());
							couponMap.put("name", coupon.getCouponName());
							couponMap.put("startTime",DateHelper.formatDate(coupon.getStartTime()));
							couponMap.put("endTime",DateHelper.formatDate(coupon.getEndTime()));
							couponMap.put("useCond", coupon.getUseCond());
							couponMap.put("amount", coupon.getAmount());
							couponMap.put("type", coupon.getType());
							//0:正常 1:已使用 2:已过期
							int state = 0;
							if(StringUtils.isNotEmpty(coupon.getIsUsed()) &&"1".equals(coupon.getIsUsed())) {
								state=1;
							}else {
								Date endDate = coupon.getEndTime();
								if(endDate.getTime()<=date.getTime())
									state=2;
							}
							couponMap.put("state", state);
							couponList.add(couponMap);
						}
	   				}
	   				resultMap.put(DATA, couponList);
	   				errorCode = SUCCESS_ERROR_CODE;
	   				errorMsg = SUCCESS_ERROR_MSG;
	   			}else{
		   			errorCode = LOGIN_ERROR_CODE;
		   			errorMsg = LOGIN_ERROR_MSG;
		   		}
	   		}
	   	}catch(Exception e){
	   		errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("OrdersdetailInterface", "mycoupon", e.toString(),"我的红包",e);
	   	}
	   	resultMap.put(CODE, errorCode);
	   	resultMap.put(MSG, errorMsg);
	   	isCrrossDomain(response);
	   	return resultMap;
	}
	
	/**  
     * 计算两个日期之间相差的天数  
     * @param smdate 较小的时间 
     * @param bdate  较大的时间 
     * @return 相差天数 
     * @throws ParseException  
     */    
    public static int daysBetween(Date smdate,Date bdate) throws ParseException    
    {    
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        smdate=sdf.parse(sdf.format(smdate));  
        bdate=sdf.parse(sdf.format(bdate));  
        Calendar cal = Calendar.getInstance();    
        cal.setTime(smdate);    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(bdate);    
        long time2 = cal.getTimeInMillis();         
        long between_days=(time2-time1)/(1000*3600*24);  
            
       return Integer.parseInt(String.valueOf(between_days));           
    }    
}